<?php

namespace app\api\controller;

use app\common\exception\ServiceException;
use app\common\model\User as UserModel;
use app\common\model\UserMaster as UserMasterModel;
use app\common\model\UserPromoter as UserPromoterModel;
use think\Db;
use app\common\service\User as UserService;

class User extends Base
{
    /**
     * 查询单个用户信息
     *
     * @return void
     */
    public function info()
    {
        $info = Db::name('user')->find($this->uid);
        if (empty($info)) {
            return self::errors('用户信息不存在');
        }
        return self::successs($info);
    }

    /**
     * 设置用户信息
     *
     * @return void
     */
    public function setting()
    {
        $data = input('post.', []);
        Db::startTrans();
        try {
            //保存数据
            $service = new UserService($this->uid, 'user');
            $res = $service->setting($this->uid, $data);
            if ($res['code'] != 1) {
                throw new \Exception($res['msg']);
            }
        } catch (ServiceException $e) {
            Db::rollback();
            $this->error($e->getMessage());
        } catch (\Exception $e) {
            Db::rollback();
            recordExceptionInfo($e);
            $this->error(config('app.app_debug') ? $e->getMessage() : '服务器错误');
        }
        Db::commit();
        return self::successs(null, '设置完成');
    }

    /**
     * 获取师傅的入驻信息
     *
     * @return void
     */
    public function master_info(){
        $info = UserMasterModel::where('uid',$this->uid)->field('uid,create_time',true)->find();
        return self::successs($info ? $info->toArray() : null);
    }

    /**
     * 获取推广的入驻信息
     *
     * @return void
     */
    public function promoter_info(){
        $info = UserPromoterModel::where('uid',$this->uid)->field('uid,create_time',true)->find();
        return self::successs($info ? $info->toArray() : null);
    }
}
